/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Vista;

import GUI.GUI_Calibracion;
import GUI.InicioAplicacion;
import java.awt.Canvas;
import java.awt.Image;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import Modelo.GoogleMaps;
import Utils.CoordUTM;
import Utils.Util;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Toolkit;
import java.io.File;
import java.io.FileOutputStream;
import javax.swing.JPanel;
import javax.swing.border.Border;

/**
 *
 * @author Fonso
 */
public class Calibracion extends Canvas implements Border {

    private String ruta;
    private Image mapa;
    private int pixelX1;
    private int pixelY1;
    private int pixelX2;
    private int pixelY2;
    private double gradosX1;
    private double gradosY1;
    private double gradosX2;
    private double gradosY2;
    private String nombreFichero;
    private Image nomap;
    private static JPanel displayMapa;

    public Calibracion() {

        displayMapa = InicioAplicacion.getControlador().getDisplayMapa();
        ruta = "";
        pixelX1 = -5;
        pixelY1 = -5;
        pixelX2 = -5;
        pixelY2 = -5;
        nomap = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/Archivos/Imagenes/nomap.jpg"));
    }

    @SuppressWarnings("static-access")
    public void comenzar() {
        JFileChooser cargarMapa = new JFileChooser();
        cargarMapa.setDialogTitle("Cargar mapa");
        FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG & PNG", "JPG", "PNG");
        cargarMapa.setFileFilter(filter);
        int seleccion = cargarMapa.showOpenDialog(displayMapa);
        if (seleccion == cargarMapa.APPROVE_OPTION) {
            mapa = Toolkit.getDefaultToolkit().getImage(cargarMapa.getSelectedFile().getPath());
            //mapa = mapa.getScaledInstance(displayMapa.getWidth(), displayMapa.getHeight(), mapa.SCALE_SMOOTH);
            ruta = cargarMapa.getSelectedFile().getPath();
            nombreFichero = cargarMapa.getSelectedFile().getName();
        }
    }

    private void paintNotFound(Graphics g) {
        //Establecemos el color de fondo y reiniciamos la pantalla
        g.setColor(new Color(0, 0, 0));
        g.fillRect(0, 0, getWidth(), getHeight());
        for (int i = 0; i <= displayMapa.getWidth() / nomap.getWidth(null); i++) {
            for (int j = 0; j <= displayMapa.getHeight() / nomap.getHeight(null); j++) {
                g.drawImage(nomap, i * nomap.getWidth(null), j * nomap.getHeight(null), null);
            }
        }
    }

    public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
        paintNotFound(g);
        if (!ruta.equals("")) {
            g.drawImage(mapa, 0, 0, displayMapa);
            g.setColor(Color.black);
            g.drawOval(pixelX1 - displayMapa.getWidth() / 2 - 10, pixelY1 - displayMapa.getHeight() / 2 - 10, 20, 20);
            g.drawOval(pixelX2 - displayMapa.getWidth() / 2 - 10, pixelY2 - displayMapa.getHeight() / 2 - 10, 20, 20);
            g.setColor(Color.red);
            g.fillOval(pixelX1 - displayMapa.getWidth() / 2 - 10, pixelY1 - displayMapa.getHeight() / 2 - 10, 20, 20);
            g.fillOval(pixelX2 - displayMapa.getWidth() / 2 - 10, pixelY2 - displayMapa.getHeight() / 2 - 10, 20, 20);
            g.setColor(Color.white);
            g.setFont(new Font("Arial", Font.BOLD, 14));
            g.drawString("1", pixelX1 - displayMapa.getWidth() / 2 - 3, pixelY1 - displayMapa.getHeight() / 2 + 5);
            g.drawString("2", pixelX2 - displayMapa.getWidth() / 2 - 3, pixelY2 - displayMapa.getHeight() / 2 + 5);
        }
        this.update(GUI_Calibracion.getDisplayMapa().getGraphics());
        this.paint(GUI_Calibracion.getDisplayMapa().getGraphics());
    }

    public Insets getBorderInsets(Component c) {
        return new Insets(0, 0, 0, 0);
    }

    public boolean isBorderOpaque() {
        return true;
    }

    public void setPixelX1(int pixel) {
        pixelX1 = pixel + (displayMapa.getWidth() / 2);
    }

    public void setPixelY1(int pixel) {
        pixelY1 = pixel + (displayMapa.getHeight() / 2);
    }

    public void setPixelX2(int pixel) {
        pixelX2 = pixel + (displayMapa.getWidth() / 2);
    }

    public void setPixelY2(int pixel) {
        pixelY2 = pixel + (displayMapa.getHeight() / 2);
    }

    public void setGradosX1(double grados) {
        gradosX1 = grados;
    }

    public void setGradosY1(double grados) {
        gradosY1 = grados;
    }

    public void setGradosX2(double grados) {
        gradosX2 = grados;
    }

    public void setGradosY2(double grados) {
        gradosY2 = grados;
    }

    public double getGradosX1() {
        return gradosX1;
    }

    public double getGradosX2() {
        return gradosX2;
    }

    public double getGradosY1() {
        return gradosY1;
    }

    public double getGradosY2() {
        return gradosY2;
    }

    @SuppressWarnings("static-access")
    public void calibrar() {
        double restaPix = Math.abs(pixelX2 - pixelX1);
        double restaGrad = Math.abs(gradosX2 - gradosX1);
        String nombreMapa = GoogleMaps.split(nombreFichero, '.')[0];
        double metrosporgrado = Math.abs(Util.LLtoUTM(23, 1, 1).getUTMEasting());
        double escala = (restaGrad * metrosporgrado) / restaPix; // metros/pixel

        CoordUTM coordenadas = Utils.Util.LLtoUTM(23, gradosY1, gradosX1);
        double latitudArribaIzq = coordenadas.getUTMNorthing() + pixelY1 * escala;
        double longitudArribaIzq = coordenadas.getUTMEasting() - pixelX1 * escala;

        double latitudArribaDer = coordenadas.getUTMNorthing() + pixelY1 * escala;
        double longitudArribaDer = coordenadas.getUTMEasting() + (mapa.getWidth(null) - pixelX1) * escala;

        double latitudAbajoIzq = coordenadas.getUTMNorthing() - (mapa.getHeight(null) - pixelY1) * escala;
        double longitudAbajoIzq = coordenadas.getUTMEasting() - pixelX1 * escala;

        double latitudAbajoDer = coordenadas.getUTMNorthing() - (mapa.getHeight(null) - pixelY1) * escala;
        double longitudAbajoDer = coordenadas.getUTMEasting() + (mapa.getWidth(null) - pixelX1) * escala;

        double gradospormetroY = Math.abs(1 / (Util.LLtoUTM(23, 1, 1).getUTMNorthing()));
        double gradospormetroX = Math.abs(1 / (Util.LLtoUTM(23, 1, 1).getUTMEasting()));

        double latitudArribaIzqGrados = gradosY1 + pixelY1 * escala * gradospormetroY;
        double longitudArribaIzqGrados = gradosX1 - pixelX1 * escala * gradospormetroX;

        double latitudArribaDerGrados = gradosY1 + pixelY1 * escala * gradospormetroY;
        double longitudArribaDerGrados = gradosX1 + (mapa.getWidth(null) - pixelX1) * escala * gradospormetroX;

        double latitudAbajoIzqGrados = gradosY1 - (mapa.getHeight(null) - pixelY1) * escala * gradospormetroY;
        double longitudAbajoIzqGrados = gradosX1 - pixelX1 * escala * gradospormetroX;

        double latitudAbajoDerGrados = gradosY1 - (mapa.getHeight(null) - pixelY1) * escala * gradospormetroY;
        double longitudAbajoDerGrados = gradosX1 + (mapa.getWidth(null) - pixelX1) * escala * gradospormetroX;

        try {
            JFileChooser guardarMapa = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("*.map", "map");
            guardarMapa.setDialogTitle("Guardar mapa");
            guardarMapa.setFileFilter(filter);
            int seleccion = guardarMapa.showSaveDialog(null);
            if (seleccion == guardarMapa.APPROVE_OPTION) {
                nombreMapa = guardarMapa.getSelectedFile().getPath();
            }
            File map;
            if (nombreMapa.endsWith(".map")){
            map = new File(nombreMapa);
            }
            else{
            map = new File(nombreMapa + ".map");
            }
            map.createNewFile();
            FileOutputStream buffer = new FileOutputStream(map);

            //Construimos el fichero .map según el estándar de OZI

            String temp = "OziExplorer Map Data File Version 2.2\n";
            temp += nombreFichero + "\n";
            temp += nombreFichero + "\n";
            temp += "1 ,Map Code, \n";
            temp += "WGS 84,, 0.0000, 0.0000,WGS 84\n";
            temp += "Reserved 1\n";
            temp += "Reserved 2\n";
            temp += "Magnetic Variation,,,E\n";
            temp += "Map Projection,(UTM) Universal Transverse Mercator,PolyCal,No,AutoCalOnly,No,BSBUseWPX,No\n";
            temp += "Point01,xy,0,0,in, deg, , ,N, , ,W, grid, 30, " + longitudArribaIzq + "," + latitudArribaIzq + ",N\n";
            temp += "Point02,xy," + mapa.getWidth(null) + ",0,in, deg, , ,N, , ,W, grid, 30, " + longitudArribaDer + ", " + latitudArribaDer + ",N\n";
            temp += "Point03,xy," + mapa.getWidth(null) + "," + mapa.getHeight(null) + ",in, deg, , ,N, , ,W, grid, 30, " + longitudAbajoDer + ", " + latitudAbajoDer + ",N\n";
            temp += "Point04,xy,0," + mapa.getHeight(null) + ",in, deg, , ,N, , ,W, grid, 30, " + longitudAbajoIzq + ", " + latitudAbajoIzq + ",N\n";
            temp += "Projection Setup,,,,,,,,,,\n";
            temp += "Map Feature = MF ; Map Comment = MC     These follow if they exist\n";
            temp += "Track File = TF      These follow if they exist\n";
            temp += "Moving Map Parameters = MM?    These follow if they exist\n";
            temp += "MM0,Yes\n";
            temp += "MMPNUM,4\n";
            temp += "MMPXY,1,0,0\n";
            temp += "MMPXY,2," + mapa.getWidth(null) + ",0\n";
            temp += "MMPXY,3," + mapa.getWidth(null) + "," +
                    mapa.getHeight(null) + "\n";
            temp += "MMPXY,4,0," + mapa.getHeight(null) + "\n";
            temp += "MMPLL,1," + longitudArribaIzqGrados + "," + latitudArribaIzqGrados + "\n";
            temp += "MMPLL,2," + longitudArribaDerGrados + "," + latitudArribaDerGrados + "\n";
            temp += "MMPLL,3," + longitudAbajoDerGrados + "," + latitudAbajoDerGrados + "\n";
            temp += "MMPLL,4," + longitudAbajoIzqGrados + "," + latitudAbajoIzqGrados + "\n";
            temp += "MM1B," + escala + "\n";
            temp += "MOP,Map Open Position,0,0\n";
            temp += "IWH,Map Image Width/Height," + mapa.getWidth(null) + "," +
                    mapa.getHeight(null);

            buffer.write(temp.getBytes());
            buffer.flush();
            buffer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
